import wsgiref.handlers
import os
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.api import mail
from google.appengine.api import users
from google.appengine.ext.webapp.util import login_required
import urllib
import re
import random
import datetime
from google.appengine.api import urlfetch
from urlparse import urlparse
import uzdb

# Reserved keys: imgs, css, url, admin, index, urlzen, app, stats, cnn, fuck, shit, damn, ass, cunt, bitch
# urls for me: jaxn, statzen, platos, pccs, pcmurf, nashville, obama, mccain, bush (worst president ever),
#							 smallbig, jackson, jacksonmiller, rickrollingisstupid 
#							 easteregg (a page with a flash game? or a picture of an easter egg, picture of a kid looking for an easter egg!!!!!)
#							 tinyurl (continuous redirect loop)
# Reserved keys for services: twitter, facebook, irc, whrrl, plurk, friendfeed, etc
#
# Delay stats up to 5 minutes for a URL using memcached
#
# redirect: self.redirect("/home")
#
# counter: http://groups.google.com/group/google-appengine/browse_thread/thread/f2ce195dc989aa2d


class MainPage(webapp.RequestHandler):
	def get(self):
		template_values = {
			'version': "app_version",
			'url': self.request.get('longtul'),
			'title': self.request.get('title'),
			'domain': self.request.domain
		}
		path = os.path.join(os.path.dirname(__file__), 'bookmarklet.html')
		self.response.out.write(template.render(path, template_values))
	
	def post(self):
		longurl = self.request.get('url')
		autocopy = self.request.get('autocopy')
		if autocopy != 'yes':
			autocopy = 'false'
		if not longurl:
			message = "url is required"
		else:
			seq = db.GqlQuery("SELECT * FROM Sequence").get()
			if not seq:
				seq = uzdb.Sequence()
				seq.url_id = 0
				seq.put()
				seq = db.GqlQuery("SELECT * FROM Sequence").get()
			
			url = db.GqlQuery("SELECT * FROM Url WHERE url = :1",longurl).get()
			if not url:
				# create the URL and slug
				url = uzdb.Url()
				url.url = longurl
				url.url_id = db.run_in_transaction(get_url_id, seq.key())
				url.slug = base10toN(url.url_id,36)
				# get the title (if the title wasn't passed in)
				try:
					url.page_title = self.request.get('title')
					url.put()
				except:
					url.page_title = longurl
					url.put()
			else:
				if not url.page_title:
					try:
						url.page_title = self.request.get('title')
						url.put()
					except:
						url.page_title = longurl
						url.put() 
			if self.request.get('send_email'):
				to_addr = self.request.get("send_email")
				if not mail.is_email_valid(to_addr):
					# Return an error message...
					message = "invalid email"
					pass

					message = mail.EmailMessage()
					message.sender = users.get_current_user().email()
					message.to = to_addr
					message.subject = title
					if self.request.get('description'):
						message.body = self.request.get(description) + "\n\nhttp://urlzen.com/"+url.slug
					else:
						message.body = "I thought you might want to read this: \n\nhttp://urlzen.com/"+url.slug
					message.send()
		#banner = get_ad()
			
		template_values = {
			'version': "app_version",
			'url': url.url,
      'title': url.page_title,
			'onload': "",
			'domain': "http://2.latest.urlzen.appspot.com"
		}
		path = os.path.join(os.path.dirname(__file__), 'bookmarklet.html')
		self.response.out.write(template.render(path, template_values))
	


#class RssPage(webapp.RequestHandler):
	
def get_ad(): 
	#return db.GqlQuery("SELECT * FROM Banner WHERE rand > :1 ORDER BY rand LIMIT 1",random.random()).get()
	return Banner()

def main():
	application = webapp.WSGIApplication(
																			 [('/bookmarklet', MainPage)])
	wsgiref.handlers.CGIHandler().run(application)

# increment counters in a transaction
def increment_counter(key, amount):
	obj = db.get(key)
	obj.counter += amount
	obj.put()
	
def get_url_id(key):
	s = db.get(key)
	if not s:
		s = uzdb.Sequence()
		s.url_id = 0
		#s.put()
	s.url_id = s.url_id + 1
	s.put()
	return s.url_id
	
def increment_domain(key,amount):
	obj = db.get(key)
	obj.domain_counter += amount
	obj.put()

# used to convery the key to base 36
def base10toN(num,n):
		"""Change a	 to a base-n number.
		Up to base-36 is supported without special notation."""
		num_rep={10:'a',11:'b',12:'c',13:'d',14:'e',15:'f',16:'g',17:'h',18:'i',19:'j',20:'k',21:'l',22:'m',23:'n',24:'o',25:'p',26:'q',27:'r',28:'s',29:'t',30:'u',31:'v',32:'w',33:'x',34:'y',35:'z'}
		new_num_string=''
		current=num
		while current!=0:
				remainder=current%n
				if 36>remainder>9:
						remainder_string=num_rep[remainder]
				elif remainder>=36:
						remainder_string='('+str(remainder)+')'
				else:
						remainder_string=str(remainder)
				new_num_string=remainder_string+new_num_string
				current=current/n
		return new_num_string

if __name__ == "__main__":
	main()